package com.buaa.rental.Controller;

import com.buaa.rental.Dao.CommonRep;
import com.buaa.rental.Util.CodeException;
import com.buaa.rental.Util.ImgUtil;
import java.util.LinkedList;
import java.util.List;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("api/img")
public class ImageController
{

	/**
	 * 上传文件
	 *
	 * @param file 上传的文件
	 * @return CommonRep 1 success 图片访问的url
	 **/
	@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
	public CommonRep uploadImage(@RequestParam("file") MultipartFile file) throws CodeException
	{
		if (file == null || file.isEmpty())
		{
			throw new CodeException("102", "上传文件不能为空");
		}
		CommonRep rep = new CommonRep();
		try
		{
			rep.setData(ImgUtil.saveFile(file));
		} catch (Exception e)
		{
			throw new CodeException("102", "文件上传错误");
		}
		return rep;
	}

	/**
	 * 上传多个文件
	 *
	 * @param file 上传的文件
	 * @return CommonRep 1 success 图片访问的url
	 **/
	@RequestMapping(value = "uploadImages", method = RequestMethod.POST)
	public CommonRep uploadImages(@RequestParam("files") List<MultipartFile> file) throws CodeException
	{
		if (file == null || file.isEmpty())
		{
			throw new CodeException("102", "上传文件不能为空");
		}
		for (MultipartFile f : file)
		{
			if (f == null || f.isEmpty())
			{
				throw new CodeException("102", "上传文件不能为空");
			}
		}
		CommonRep rep = new CommonRep();
		try
		{
			List<String> res = new LinkedList<>();
			for (MultipartFile f : file)
			{
				res.add(ImgUtil.saveFile(f));
			}
			rep.setData(res);
		} catch (Exception e)
		{
			throw new CodeException("102", "文件上传错误");
		}
		return rep;
	}
}

